package com.chen.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.chen.model.dto.h5.UserRegisterDto;
import com.chen.model.dto.system.LoginDto;
import com.chen.model.entity.user.UserInfo;
import com.chen.model.vo.common.ResultCodeEnum;
import com.chen.model.vo.h5.UserInfoVo;
import com.chen.service.exception.MyException;
import com.chen.service.util.AuthContextUtil;
import com.chen.user.mapper.UserMapper;
import com.chen.user.service.UserService;
import com.chen.util.IpUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;

/**
 * @author cgj
 * @date 4/17/25 2:55 PM
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 用户注册
     *
     * @param userRegisterDto
     */
    @Override
    public void register(UserRegisterDto userRegisterDto) {
        //验证码信息是否为空, 后端可以不做
        String username = userRegisterDto.getUsername();
        String code = userRegisterDto.getCode();
        String nickName = userRegisterDto.getNickName();
        String password = userRegisterDto.getPassword();
        if (StringUtils.isEmpty(username) ||
                StringUtils.isEmpty(code) ||
                StringUtils.isEmpty(nickName) ||
                StringUtils.isEmpty(password)) {
            throw new MyException(ResultCodeEnum.DATA_ERROR);
        }
        //通过手机号就redis中查询验证码
        String redisCode = redisTemplate.opsForValue().get("phone:code" + username);

        if (!code.equals(redisCode)) {
            //说明验证码没有匹配验证码错误
            throw new MyException(ResultCodeEnum.VALIDATECODE_ERROR);
        }
        //验证用户时候存在
        Integer row = userMapper.selectByUserName(username);
        if (row > 0) {
            throw new MyException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }


        //对数据进行封装
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userRegisterDto, userInfo);  // 把参数1的属性值复制到参数2中
        userInfo.setStatus(1);
        userInfo.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        userInfo.setPhone(username);
        userInfo.setSex(1);
        //DigestUtils , BeanUtils 都是spring提供的

        //保存用户
        userMapper.savaUser(userInfo);

        // 删除验证码
        redisTemplate.delete("phone:code" + username);
    }

    /**
     * 用户登录
     * @param loginDto
     * @param req
     * @return
     */
    @Override
    public String login(LoginDto loginDto, HttpServletRequest req) {
        //获取ip地址
        String ipAddress = IpUtil.getIpAddress(req);
        //对数据进行非空判断
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        if(StringUtils.isEmpty(userName)|| StringUtils.isEmpty(password)){
             throw  new MyException(ResultCodeEnum.DATA_ERROR);
        }
        // 根据用户名去数据库中查询
        UserInfo  user =userMapper.getUserName(userName);
        if(user==null){
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
        }
        //判断状态
        if(user.getStatus()==0){
            throw  new MyException(ResultCodeEnum.ACCOUNT_STOP);
        }
        //对比密码
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if(!md5Password.equals(user.getPassword())){
            throw new MyException(ResultCodeEnum.LOGIN_ERROR);
        }
        // 验证全部成功,生成token
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //补充信息
        user.setLastLoginIp(ipAddress);
        user.setLastLoginTime(new Date());
        //存储到redis
        redisTemplate.opsForValue().set("user:login:"+token, JSON.toJSONString(user));
        //更新用户信息到数据库
        userMapper.updateInfo(user);

        return token;

    }

    /**
     * 登录后获取用户信息
     * @param token
     * @return
     */

//    @Override
//    public UserInfoVo getCurrentUserInfo(String token) {
//        String userJson = redisTemplate.opsForValue().get("user:login:" + token);
//        //查不到说明用户没有登录
//        if(StringUtils.isEmpty(userJson)){
//            throw new MyException(ResultCodeEnum.LOGIN_AUTH);
//        }
//        UserInfo userInfo = JSON.parseObject(userJson, UserInfo.class);
//        // 拷贝对象
//        UserInfoVo userInfoVo = new UserInfoVo();
//        BeanUtils.copyProperties(userInfo,userInfoVo);
//        return userInfoVo;
//    }

    /**
     * 改造的方法, 从localThread中直接拿用户信息
     * @param token
     * @return
     */
    @Override
    public UserInfoVo getCurrentUserInfo(String token) {
        //从localThread中直接拿用户信息 ,因为我们已经在拦截器进行处理
        UserInfo userInfo = AuthContextUtil.get();
        // 拷贝对象
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo,userInfoVo);
        return userInfoVo;
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));
    }
}
